import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'

//定义store
export const useTasklistStore = defineStore('tasklist', () => {
  //任务列表
  // var tasklist = ref([]);
  var tasklist = reactive([]);

  var title = ref('');

  //统计未完成的任务数量
  var unFinishedCount = computed(()=>{
    // return tasklist.value.filter((item)=>!item.status).length;
    return tasklist.filter((item)=>!item.status).length;
  })

  //新增任务
  var addTask = (payload)=>{ //payload是传来的任务名称
    // tasklist.value.push( { id: tasklist.value.length + 1, name: payload, status: false } );
    tasklist.push( { id: tasklist.length + 1, name: payload, status: false } );
  }

  //更改任务状态
  var changeStatus = (payload)=>{ //payload是传来的任务id
    //查找任务
    // var task =  tasklist.value.find((item)=>{
    //   return item.id == payload;
    // })
    var task =  tasklist.find((item)=>{
      return item.id == payload;
    })
    if( task ){
      task.status = !task.status;
    }
  }

  //删除任务
  var deleteTask = (payload)=>{ //payload是传来的任务id
    //查找任务
    // var index =  tasklist.value.findIndex((item)=>{
    //   return item.id == payload;
    // })
    // if( index != -1 ){
    //   tasklist.value.splice(index,1);
    // }
    var index =  tasklist.findIndex((item)=>{
      return item.id == payload;
    })
    if( index != -1 ){
      tasklist.splice(index,1);
    }
  }

  //必须return , 组件中才可以拿到这些数据和方法
  return {
    title,
    tasklist,
    unFinishedCount,
    addTask,
    changeStatus,
    deleteTask
  }
})
